package cn.iocoder.yudao.module.biz.controller.admin.pay;

import cn.iocoder.yudao.framework.common.pojo.PageParam;
import cn.iocoder.yudao.framework.dict.core.DictFrameworkUtils;
import cn.iocoder.yudao.framework.excel.core.util.poi.ExcelUtilRuoyi;
import cn.iocoder.yudao.module.biz.controller.admin.contract.vo.ContractArchivePageReqVO;
import cn.iocoder.yudao.module.biz.controller.admin.pay.domain.SanBizPaymentManagement;
import cn.iocoder.yudao.module.biz.controller.admin.pay.service.SanBizPaymentManagementService;
import cn.iocoder.yudao.module.biz.controller.admin.receivables.domain.SanBizContractArchiveReceiveRecord;
import cn.iocoder.yudao.module.biz.controller.admin.receivables.service.SanBizContractArchiveReceiveRecordService;
import cn.iocoder.yudao.module.biz.dal.dataobject.contract.ContractArchiveDO;
import cn.iocoder.yudao.module.biz.service.contract.ContractArchiveService;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import io.swagger.v3.oas.annotations.Parameters;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.security.access.prepost.PreAuthorize;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Operation;

import javax.validation.*;
import javax.servlet.http.*;
import java.util.*;
import java.io.IOException;

import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;

import cn.iocoder.yudao.framework.excel.core.util.ExcelUtils;

import cn.iocoder.yudao.framework.apilog.core.annotation.ApiAccessLog;
import org.springframework.web.multipart.MultipartFile;

import static cn.iocoder.yudao.framework.apilog.core.enums.OperateTypeEnum.*;

@Tag(name = "管理后台 - 收款管理")
@RestController
@RequestMapping("/pay/biz-payment-management")
@Validated
public class BizPaymentManagementController {

    @Resource
    private SanBizPaymentManagementService bizPaymentManagementService;

    @Resource
    private SanBizContractArchiveReceiveRecordService contractArchiveReceiveRecordService;

    @Resource
    private ContractArchiveService contractArchiveService;

    @PostMapping("/create")
    @Operation(summary = "创建收款管理")
    @PreAuthorize("@ss.hasPermission('pay:biz-payment-management:create')")
    @Transactional
    public CommonResult<Long> createBizPaymentManagement(@Valid @RequestBody SanBizPaymentManagement createReqVO) {
        bizPaymentManagementService.save(createReqVO);
        UpdateWrapper wrapper = new UpdateWrapper();
        wrapper.set("status","1");
        wrapper.eq("id", createReqVO.getContractId());
        contractArchiveReceiveRecordService.update(wrapper);
        return success(1l);
    }

    @PutMapping("/update")
    @Operation(summary = "更新收款管理")
    @PreAuthorize("@ss.hasPermission('pay:biz-payment-management:update')")
    @Transactional
    public CommonResult<Boolean> updateBizPaymentManagement(@Valid @RequestBody SanBizPaymentManagement updateReqVO) {
        bizPaymentManagementService.updateById(updateReqVO);
        UpdateWrapper wrapper = new UpdateWrapper();
        wrapper.set("status","1");
        wrapper.eq("id", updateReqVO.getContractId());
        contractArchiveReceiveRecordService.update(wrapper);
        return success(true);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除收款管理")
    @Parameter(name = "id", description = "编号", required = true)
    @PreAuthorize("@ss.hasPermission('pay:biz-payment-management:delete')")
    public CommonResult<Boolean> deleteBizPaymentManagement(@RequestParam("id") Long id) {
        bizPaymentManagementService.removeById(id);
        return success(true);
    }

    @DeleteMapping("/delete-list")
    @Parameter(name = "ids", description = "编号", required = true)
    @Operation(summary = "批量删除收款管理")
                @PreAuthorize("@ss.hasPermission('pay:biz-payment-management:delete')")
    public CommonResult<Boolean> deleteBizPaymentManagementList(@RequestParam("ids") List<Long> ids) {
        bizPaymentManagementService.removeByIds(ids);
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得收款管理")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('pay:biz-payment-management:query')")
    public CommonResult<SanBizPaymentManagement> getBizPaymentManagement(@RequestParam("id") Long id) {
        SanBizPaymentManagement bizPaymentManagement = bizPaymentManagementService.getById(id);
        return success(BeanUtils.toBean(bizPaymentManagement, SanBizPaymentManagement.class));
    }

    @GetMapping("/getBizContractArchiveList")
    @Operation(summary = "获得合同列表")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('pay:biz-payment-management:query')")
    public CommonResult<List<ContractArchiveDO>> getBizContractArchiveList() {
        ContractArchivePageReqVO pageReqVO = new ContractArchivePageReqVO();
        pageReqVO.setStatus("2"); // 生效的合同
        pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        List<ContractArchiveDO> list = contractArchiveService.getContractArchivePage(pageReqVO).getList();
        return success(list);
    }


    @GetMapping("/page")
    @Operation(summary = "获得收款管理分页")
    @PreAuthorize("@ss.hasPermission('pay:biz-payment-management:query')")
    public CommonResult<IPage<SanBizPaymentManagement>> getBizPaymentManagementPage(@Valid SanBizPaymentManagement pageReqVO) {
        QueryWrapper w = new QueryWrapper(pageReqVO);
        IPage<SanBizPaymentManagement> pageResult = bizPaymentManagementService.getBizPaymentManagementPage(pageReqVO);
        return success(pageResult);
    }

    @GetMapping("/export-excel")
    @Operation(summary = "导出收款管理 Excel")
    @PreAuthorize("@ss.hasPermission('pay:biz-payment-management:export')")
    @ApiAccessLog(operateType = EXPORT)
    public void exportBizPaymentManagementExcel(@Valid SanBizPaymentManagement pageReqVO,
              HttpServletResponse response) throws IOException {
//        pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        QueryWrapper w = new QueryWrapper(pageReqVO);
        List<SanBizPaymentManagement> list = bizPaymentManagementService.list(w);
        // 导出 Excel
//        ExcelUtils.write(response, "打款记录.xls", "数据", SanBizPaymentManagement.class,
//                        BeanUtils.toBean(list, SanBizPaymentManagement.class));
        ExcelUtilRuoyi<SanBizPaymentManagement> util = new ExcelUtilRuoyi<SanBizPaymentManagement>(SanBizPaymentManagement.class);
        util.exportExcel(response, list, "打款记录");

    }


    @GetMapping("/get-import-template")
    @Operation(summary = "获得导入打款记录模板")
    public void importTemplate(HttpServletResponse response) throws IOException {
        HashMap<String,String[]> map = new HashMap<>();
        String[] outDataType = DictFrameworkUtils.getDictDataLabelList("biz_pay_service_type").toArray(new String[0]);
        if (outDataType!=null) {
            map.put("biz_pay_service_type",outDataType);
        }
        ExcelUtilRuoyi<SanBizPaymentManagement> util = new ExcelUtilRuoyi<SanBizPaymentManagement>(SanBizPaymentManagement.class,map);
        util.importTemplateExcel(response, "打款记录");
    }

    @PostMapping("/import")
    @Operation(summary = "导入打款记录")
    @Parameters({
            @Parameter(name = "file", description = "Excel 文件", required = true),
            @Parameter(name = "updateSupport", description = "是否支持更新，默认为 false", example = "true")
    })
    @PreAuthorize("@ss.hasPermission('pay:biz-payment-management:export')")
    public CommonResult<String> importExcel(@RequestParam("file") MultipartFile file,
                                                      @RequestParam(value = "updateSupport", required = false, defaultValue = "false") Boolean updateSupport) throws Exception {
        ExcelUtilRuoyi<SanBizPaymentManagement> util = new ExcelUtilRuoyi<SanBizPaymentManagement>(SanBizPaymentManagement.class);
        List<SanBizPaymentManagement> userList = util.importExcel(file.getInputStream());
        String message = bizPaymentManagementService.importList(userList, updateSupport);
        return success(message);
    }
}
